﻿@page "/login"
@inject NavigationManager NavigationManager
@inject IJSRuntime JSRuntime
@inject IHttpClientFactory HttpClientFactory
@inject AuthenticationStateService AuthenticationStateService
@using System.ComponentModel.DataAnnotations
@using System.Text.Json.Serialization;

<div class="login-container">
    <div class="login-box">
        <div class="logo">
            <img src="/logo.png" alt="Logo" class="logo-image" />
        </div>
        <h2 class="login-title">系统登录</h2>

        <EditForm Model="@loginForm" OnValidSubmit="HandleLogin">
            <DataAnnotationsValidator />
            <ValidationSummary />

            <div class="form-group">
                <label for="email">邮箱</label>
                <InputText @bind-Value="loginForm.Email" id="email" class="form-control custom-input" placeholder="请输入邮箱" />
                <ValidationMessage For="@(() => loginForm.Email)" />
            </div>

            <div class="form-group">
                <label for="password">密码</label>
                <InputText @bind-Value="loginForm.Password" id="password" type="password" class="form-control custom-input" placeholder="请输入密码" />
                <ValidationMessage For="@(() => loginForm.Password)" />
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-primary login-btn" disabled="@loading">
                    @if (loading)
                    {
                        <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                        <span>登录中...</span>
                    }
                    else
                    {
                        <span>登录</span>
                    }
                </button>
            </div>

            <div class="action-links">
                <a href="/change-password" class="action-link">忘记密码?</a>
                <a href="/register" class="action-link">立即注册</a>
            </div>
        </EditForm>
    </div>
</div>

@code {
    private LoginModel loginForm = new LoginModel();
    private bool loading = false;

    public class LoginModel
    {
        [Required(ErrorMessage = "请输入邮箱")]
        [EmailAddress(ErrorMessage = "请输入有效的邮箱地址")]
        public string Email { get; set; }

        [Required(ErrorMessage = "请输入密码")]
        [MinLength(6, ErrorMessage = "密码长度不能少于6位")]
        public string Password { get; set; }
    }

    private async Task HandleLogin()
    {
        loading = true;

        try
        {
            var httpClient = HttpClientFactory.CreateClient("Api");

            // 1. 先调用登录接口
            var loginResponse = await httpClient.PostAsJsonAsync(
                "/api/user/login",
                new { email = loginForm.Email, password = loginForm.Password }
            );

            var loginResponseContent = await loginResponse.Content.ReadAsStringAsync();
            Console.WriteLine($"Login API 返回: {loginResponseContent}");

            if (loginResponse.IsSuccessStatusCode)
            {
                var loginResult = await loginResponse.Content.ReadFromJsonAsync<LoginResponse>();

                if (loginResult?.Success == true)
                {
                    // 2. 登录成功后，调用 /api/token 获取 Token
                    var tokenResponse = await httpClient.GetAsync("/api/token");


                    var tokenResponseContent = await tokenResponse.Content.ReadAsStringAsync();
                    Console.WriteLine($"Token API 返回: {tokenResponseContent}");

                    if (tokenResponse.IsSuccessStatusCode)
                    {
                        var tokenResult = await tokenResponse.Content.ReadFromJsonAsync<TokenResponse>();

                        if (tokenResult?.Token != null)
                        {
                            // 3. 将 Token 存入 AuthenticationStateService
                            await AuthenticationStateService.SetTokenAsync(tokenResult.Token);

                            // 4. 存储其他用户信息（可选）
                            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "isAuthenticated", "true");
                            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "userId", loginResult.Data.UserId);
                            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "username", loginResult.Data.Username);
                            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "email", loginResult.Data.Email);
                            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "role", loginResult.Data.Role);
                            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "isGuest", "false");

                            // 5. 跳转到首页
                            NavigationManager.NavigateTo("/home");
                        }
                        else
                        {
                            await JSRuntime.InvokeVoidAsync("alert", "获取 Token 失败");
                        }
                    }
                    else
                    {
                        await JSRuntime.InvokeVoidAsync("alert", "获取 Token 失败");
                    }
                }
            }
            else
            {
                var errorResponse = await loginResponse.Content.ReadFromJsonAsync<ErrorResponse>();
                var errorMessage = loginResponse.StatusCode switch
                {
                    System.Net.HttpStatusCode.BadRequest => "请检查输入信息是否正确",
                    System.Net.HttpStatusCode.Unauthorized => errorResponse?.Message?.Contains("未注册") == true ||
                                                             errorResponse?.Message?.Contains("未激活") == true
                                                             ? "邮箱未注册或账户未激活"
                                                             : "密码错误",
                    System.Net.HttpStatusCode.InternalServerError => "服务器错误，请稍后重试",
                    _ => "登录失败，请稍后重试"
                };

                await JSRuntime.InvokeVoidAsync("alert", errorMessage);
            }
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", "网络错误，请检查网络连接");
            Console.WriteLine(ex.Message);
        }
        finally
        {
            loading = false;
        }
    }

    public class LoginResponse
    {
        public bool Success { get; set; }
        public UserData Data { get; set; }
    }

    public class TokenResponse
    {
        public string Expires_at { get; set; }
        public string Token { get; set; }
    }

    public class UserData
    {
        public int UserId { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public string Role { get; set; }
    }

    public class ErrorResponse
    {
        public string Message { get; set; }
    }
}

<style>
    .login-container {
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
        background-color: #f0f2f5;
        background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    }

    .login-box {
        width: 100%;
        max-width: 420px;
        padding: 30px 20px;
        border-radius: 12px;
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
        border: none;
        background-color: rgba(255, 255, 255, 0.95);
    }

    .logo {
        text-align: center;
        margin-bottom: 20px;
    }

    .logo-image {
        height: 70px;
        width: auto;
        max-width: 100%;
        object-fit: contain;
        border-radius: 40px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .login-title {
        text-align: center;
        color: #2c3e50;
        margin-bottom: 25px;
        font-weight: 600;
        font-size: 22px;
        letter-spacing: 0.5px;
    }

    .custom-input {
        border-radius: 8px;
        height: 44px;
        line-height: 44px;
        padding: 0 15px;
        border: 1px solid #dcdfe6;
        width: 100%;
    }

        .custom-input:focus {
            border-color: #409eff;
            outline: none;
        }

    .form-group {
        margin-bottom: 20px;
    }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #606266;
            font-size: 14px;
        }

    .login-btn {
        width: 100%;
        margin-top: 10px;
        height: 44px;
        font-size: 16px;
        border-radius: 8px;
        background-color: #409eff;
        border-color: #409eff;
        transition: all 0.3s;
        color: white;
        border: none;
        cursor: pointer;
    }

        .login-btn:hover {
            background-color: #66b1ff;
            border-color: #66b1ff;
        }

        .login-btn:disabled {
            background-color: #a0cfff;
            cursor: not-allowed;
        }

    .action-links {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        flex-wrap: wrap;
    }

    .action-link {
        color: #409eff;
        font-size: 14px;
        margin: 5px 0;
        white-space: nowrap;
        text-decoration: none;
    }

        .action-link:hover {
            color: #66b1ff;
            text-decoration: underline;
        }
</style>